package cn.teduymdj.passport.security;

import cn.teduymdj.passport.mapper.UserMapper;
import cn.teduymdj.passport.pojo.vo.UserLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security框架自动调用UserDetailsServiceImpl中的loadUserByUsername方法，参数：{}", s);
        UserLoginInfoVO loginInfo = userMapper.getLoginInfo(s);
        log.debug("从数据库中根据用户名【{}】查询管理员信息，结果：{}", s, loginInfo);
        if (loginInfo == null) {
            log.debug("没有与用户名匹配的信息,即将抛异常");
            String message = "登录失败,用户名不存在";
            throw new BadCredentialsException(message);
        }



        Long id = loginInfo.getId();
        String username = loginInfo.getUsername();
        String password = loginInfo.getPassword();
        boolean enable = loginInfo.getEnable() == 1;
        List<String> permissions = loginInfo.getPermissions();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissions) {
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        UserDetails userDetails = new MyUserDetails(id, username, password, enable, authorities);
        log.debug("即将向Spring Security框架返回UserDetails对象：{}", userDetails);
        return userDetails;
    }

}
